//
//  StatusDAL.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/22.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import Foundation

//最大缓存时间
private let maxCacheDateTime: NSTimeInterval =  7 * 24 * 60 * 60

class StatusDAL {

    
    //清理过期的缓存数据
    class func clearDataCache() {
    
        let date = NSDate(timeIntervalSinceNow: -maxCacheDateTime)
        
        //时间转换器
        let df = NSDateFormatter()
        
        //指定时区
        df.locale = NSLocale(localeIdentifier: "en")
        
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        //获取时期结果
        let dateStr = df.stringFromDate(date)
        
        //准备SQL
        let sql = "DELETE FROM T_Status WHERE createTime < ?;"
        
        SQLiteManager.sharedManager.queue.inDatabase { (db) -> Void in
            if db.executeUpdate(sql, dateStr) {
            
                print("删除了 \(db.changes()) 条数据缓存")
            }
            
        }
    
    }
    
    
    /// 加载微博数据
    class func loadStatus(since_id: Int, max_id: Int, finished: (array: [[String: AnyObject]]?) -> ()) {
    
        //1.检查本地是否存在缓存数据
        let array = checkChacheData(since_id, max_id: max_id)
        

        //2.如果有,就返回缓存数据
        if array?.count > 0 {
        
            print("查询到缓存数据 \(array!.count)")
            
            finished(array: array)
        
            return
        }
        
        //3.如果没有,就加载网络数据
        NetworkTools.sharedTools.loadStatus (since_id: since_id, max_id: max_id){ (result, error) -> () in
            
            if error != nil {
                
                print("出错")
                
                finished(array: nil)
                
                return
                
            }
            
            //获取数据
            guard let array = result?["statuses"] as? [[String: AnyObject]] else  {
                
                print("格式错误---")
                
                finished(array: nil)
                
                return
                
            }
            //4.将网络返回的数据,保存在本地数据库
            StatusDAL.saveCacheData(array)
            
            //5.返回网络数据
            finished(array: array)
        }
        
    
    
    }


    /// 检查本地数据库中,是否存在需要的数据
    private class func checkChacheData(since_id: Int, max_id: Int) ->[[String: AnyObject]]? {
    
        //1.用户id
        guard let userId = UserAccountViewModel.sharedUserAccount.account?.uid else {
            print("用户没有登录")
            return nil
        }
        
        //2.准备SQL
        var sql = "SELECT statusId, status, userId FROM T_Status \n"
        sql += "WHERE userId = \(userId) \n"
        
        if since_id > 0 {           // 下拉刷新
            sql += "    AND statusId > \(since_id) \n"
        } else if max_id > 0 {      // 上拉刷新
            sql += "    AND statusId < \(max_id) \n"
        }
        
        sql += "ORDER BY statusId DESC LIMIT 20;"
        
        //执行SQL ->返回结果集合
        let array = SQLiteManager.sharedManager.execRecordSet(sql)
        
        //遍历数组,获取数据
        var arrayM = [[String: AnyObject]]()
        
        for dict in array {
        
            let jsonData = dict["status"] as! NSData
            
            let result = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
        
            //添加到数组中
            arrayM.append(result as! [String : AnyObject])
        }
        
        return arrayM
    
    
    }

    
    
    
    ///保存网络数据到本地数据库
    private class func saveCacheData(array: [[String: AnyObject]]) {
    
        //1.用户id
        guard let userId = UserAccountViewModel.sharedUserAccount.account?.uid else {
            print("用户没有登录")
            return
        }
    
        //准备SQL
        
        let sql = "INSERT OR REPLACE INTO T_Status (statusId, status, userId) VALUES (?, ?, ?);"
        
        //遍历数组 批量插入数据
        SQLiteManager.sharedManager.queue.inTransaction { (db, rollback) -> Void in
            
            for dict in array {
            
                //1.微博id
                let statusId = dict["id"] as! Int
                
                //序列化字典
                let json = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
                
                //插入数据
                if !db.executeUpdate(sql, statusId,json,userId) {
                
                    print("插入数据失败")
                    //回滚
                    rollback.memory = true
                    break
                    
                }
            
            }
            
        }
    
        print("数据插入完成!")
    }
    



}